// pages/applist/applist.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    applist: [],
    tipsContent: "",
    tipsType: "",
    showTips: false,
    name: '电视盒子'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.clear();
    this.getAppList();
    this.getName();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.clear();
    this.getAppList();
  },
  clear() {
    this.setData({
      applist: []
    })
  },
  getAppList() {
    let that = this;
    var list = [];
    this.getAction("/v1/applist", function (res) {
      //console.log(res)
      const apps = res.data.apps;
      //console.log(apps)
      //console.log(that)
      for (let i = 0; i < res.data.count; i++) {
        const element = apps[i];
        list.push({
          icon: "http://" + getApp().globalData.host + ":8080/v1/appicon?appid=" + element.appid,
          text: element.name,
          activity: element.activity,
          package: element.package
        });
        ////console.log(that.data.applist[i].icon)
      }
      list.sort(function (a, b) {
        return a.text.localeCompare(b.text);
      })
      that.setData({
        applist: list
      });
      setTimeout(() => {
        // 取消页面刷新动画
        wx.stopPullDownRefresh();
      }, 300);
    });
  },
  getName() {
    let that = this;
    this.getAction("/v1/status", function (params) {
      //console.log("获取设备名称")
      //console.log(params)
      if (params.statusCode == 200) {
        that.setData({
          name: params.data.name
        });
      }
    })
  },
  getAction(url, callback) {
    wx.request({
      url: 'http://' + getApp().globalData.host + ':8080' + url,
      method: 'GET',
      complete: callback
    })
  },
  postAction(url, data, callback) {
    wx.request({
      url: 'http://' + getApp().globalData.host + ':8080' + url,
      method: 'POST',
      data: data,
      headers: {
        'content-type': 'application/json ;charset=utf-8' //默认值
      },
      dataType: 'json',
      complete: callback
    });
  },
  openApp(e) {
    //console.log(e)
    let that = this;
    var app = this.data.applist[e.currentTarget.id];
    var data = {
      package: app.package,
      activity: app.activity
    };
    this.postAction("/v1/application", data, function (res) {
      //console.log(res)
      if (res.statusCode == 200) {
        that.setData({
          showTips: true,
          tipsType: "success",
          tipsContent: "应用已打开"
        });
      } else {
        that.setData({
          showTips: true,
          tipsType: "error",
          tipsContent: "应用打开失败"
        });
      }
    });
  }
})